const { sys_notice_model: SysNoticeModel } = require('../models');
const { Op } = require('sequelize');
const { realDelete } = require('../config/system');
const DateUtils = require('../utils/dateUtils');

class NoticeService {
    /**
     * 创建通知公告
     * @param {Object} noticeData 通知数据
     */
    async createNotice(noticeData) {
        return await SysNoticeModel.create(noticeData);
    }

    /**
     * 更新通知公告
     * @param {number} id 通知ID
     * @param {Object} noticeData 通知数据
     */
    async updateNotice(id, noticeData) {
        return await SysNoticeModel.update(noticeData, {
            where: { id, is_deleted: 0 }
        });
    }

    /**
     * 删除通知公告
     * @param {number} id 通知ID
     */
    async deleteNotice(id) {
        const notice = await SysNoticeModel.findByPk(id);
        if (!notice) {
            throw new Error('通知数据不存在');
        }
        if (realDelete) {
            // 真实删除
            await notice.destroy();
        } else {
            // 软删除
            await notice.update({
                is_deleted: 1,
                update_time: DateUtils.getCurrentTime()
            });
        }
    }

    /**
     * 获取通知公告详情
     * @param {number} id 通知ID
     */
    async getNoticeById(id) {
        return await SysNoticeModel.findOne({
            where: { id, is_deleted: 0 }
        });
    }

    /**
     * 获取通知公告列表
     * @param {Object} query 查询条件
     */
    async getNoticeList(query) {
        const { title, type, level, publish_status, page = 1, limit = 10 } = query;
        const where = { is_deleted: 0 };

        if (title) {
            where.title = { [Op.like]: `%${title}%` };
        }
        if (type !== undefined) {
            where.type = type;
        }
        if (level) {
            where.level = level;
        }
        if (publish_status !== undefined) {
            where.publish_status = publish_status;
        }

        const { count, rows } = await SysNoticeModel.findAndCountAll({
            where,
            offset: (page - 1) * limit,
            limit: parseInt(limit),
            order: [['create_time', 'DESC']]
        });

        return {
            list: rows,
            total: count,
            page: parseInt(page),
            limit: parseInt(limit)
        };
    }

    /**
     * 发布通知公告
     * @param {number} id 通知ID
     */
    async publishNotice(id) {
        return await SysNoticeModel.update(
            { 
                publish_status: 1,
                publish_time: DateUtils.getCurrentTime()
            },
            { where: { id, is_deleted: 0 } }
        );
    }

    /**
     * 撤回通知公告
     * @param {number} id 通知ID
     */
    async revokeNotice(id) {
        return await SysNoticeModel.update(
            { 
                publish_status: -1,
                revoke_time: DateUtils.getCurrentTime()
            },
            { where: { id, is_deleted: 0 } }
        );
    }
}

module.exports = new NoticeService();